package com.huluobo.a2207parkdemo.patrol

import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TimePicker
import android.widget.Toast
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2207parkdemo.R
import com.huluobo.a2207parkdemo.adapter.PointAdapter
import com.huluobo.a2207parkdemo.databinding.ActivityAddPatrolBinding
import com.huluobo.base.bean.PPointBean
import com.huluobo.base.bean.PPointBeanItem
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.StringBuilder
import java.util.Calendar

@AndroidEntryPoint
class AddPatrolActivity : BaseActivity<ActivityAddPatrolBinding, PatrolViewModel>() {
    private var startTime = 0L
    private var endTime = 0L
    private var time = 0L
    private lateinit var pointAdapter: PointAdapter

    private val calendar = Calendar.getInstance().apply {
        set(Calendar.HOUR, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }

    override fun initData() {
        vm.getAllPoint()
        vm.getAllPointSuccess.observe(this) {
            val list = Gson().fromJson(it, PPointBean::class.java)
            pointAdapter.data.clear()
            pointAdapter.data.addAll(list)
            pointAdapter.notifyDataSetChanged()
        }

        vm.addPatrolSuccess.observe(this) {
            ToastUtils.showLong("添加成功")
            finish()
        }
    }

    override fun initView() {
        binding.addPatrolHeader.headerTitle.text = "添加巡更路线"
        binding.addPatrolHeader.headerBack.setOnClickListener { finish() }

        binding.addPatrolRv.layoutManager = GridLayoutManager(this, 2)
        pointAdapter = PointAdapter()
        binding.addPatrolRv.adapter = pointAdapter

        binding.addPatrolStartTimeIv.setOnClickListener {
            TimePickerDialog(this, { _, hourOfDay, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                calendar.set(Calendar.MINUTE, minute)
                startTime = calendar.timeInMillis//将选中的时间赋值给开始时间
                binding.addPatrolStartTimeNowTv.text = "$hourOfDay:$minute"
            }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show()
        }

        binding.addPatrolEndTimeIv.setOnClickListener {
            TimePickerDialog(this, { _, hourOfDay, minute ->
                calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                calendar.set(Calendar.MINUTE, minute)
                endTime = calendar.timeInMillis//将选中的时间赋值给开始时间
                binding.addPatrolEndTimeNowTv.text = "$hourOfDay:$minute"

                time = endTime - startTime
                if (time <= 0 || startTime == 0L) {
                    ToastUtils.showLong("请重新选择时间")
                } else {
                    val newTime = time / 1000 / 60 / 60
                    binding.addPatrolTimeNowTv.text = "${newTime}小时"
                }
            }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true).show()
        }

        val newPointList = mutableListOf<PPointBeanItem>()
        val pointLiveData = MutableLiveData<List<PPointBeanItem>>()

        pointAdapter.setOnItemClickListener { adapter, view, position ->
            val pointBeanItem = pointAdapter.data[position]
            newPointList.add(pointBeanItem)
            pointLiveData.postValue(newPointList)
        }

        pointLiveData.observe(this) {
            val points = StringBuilder()
            newPointList.forEach {
                points.append(it.pointName)
                points.append(",")
            }
            points.deleteCharAt(points.length - 1)
            binding.addPatrolChoicePointResultTv.text = points.toString()
        }

        binding.addPatrolCommitBtn.setOnClickListener {
            val pStart = binding.addPatrolStartTimeNowTv.text.toString()
            val pEnd = binding.addPatrolEndTimeNowTv.text.toString()
            val pTime = binding.addPatrolTimeNowTv.text.toString()
            val pPoint = Gson().toJson(newPointList)
            Log.i("TagA", "pPoint:${pPoint.toString()}")

            if (pStart.isNotEmpty() && pEnd.isNotEmpty() && pTime.isNotEmpty() && pPoint.isNotEmpty()) {
                val map = mutableMapOf<String, Any>()
                map[Const.PARAM_PATROL_START] = pStart
                map[Const.PARAM_PATROL_END] = pEnd
                map[Const.PARAM_PATROL_TIME] = pTime
                map[Const.PARAM_PATROL_POINT] = pPoint
                map[Const.PARAM_PATROL_GROUP_ID] = 50

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.addPatrol(body)
            }
        }
    }
}